<template>
  <van-form @submit="onSubmit">
    <van-field autocomplete="off"
      v-model="company_name"
      name="company_name"
      label="企业名称"
      placeholder="请输入企业名称"
      required
      :rules="[{required: true, message: '未填写'}]"
      :readonly="disabled"
    />

    <van-field autocomplete="off" name="company_logo" label="公司logo或门头照片" :readonly="disabled">
      <template #input>
        <van-uploader
          :show-upload="!disabled"
          @delete="toDeleteAnyPreviewPhoto_company_logo"
          :preview-options="{
            closeable: true,
          }"
          v-model="company_logo"
          :max-count="9"
          :after-read="uploadCompanyImg_logo"
          :deletable="deletable"
        />
      </template>
    </van-field>

    <com-full-address
      :frontLabel="'企业'"
      :showFullAddressObj="showFullAddressObj"
      @getFullAddressValue="toGetFullAddress_company"
      @updateRegionFourName="toUpdateRegionFourName"
      @updateDetailAddress="toUpdateDetailAddress"
      :readonly="disabled"
      :isUpdate="isUpdate"
      :isRequired="true"
    ></com-full-address>

    <van-field autocomplete="off"
      v-model="company_phone"
      name="company_phone"
      type="number"
      label="企业电话"
      placeholder="请输入企业电话"
      required
      :rules="[{required: true, message: '请填写'}]"
      :readonly="disabled"
    />
    <van-field autocomplete="off"
      v-model="legal_name"
      name="legal_name"
      label="法人"
      placeholder="请输入法人"
      required
      :rules="[{required: true, message: '请填写'}]"
      :readonly="disabled"
    />
    <van-field autocomplete="off"
      v-model="legal_name_phone"
      name="legal_name_phone"
      required
      type="number"
      label="法人手机号"
      placeholder="请输入法人手机号"
      :readonly="disabled"
      :rules="[
        {required: true, message: '法人手机号未填写'},
        {pattern: phoneReg, message: '请输入正确手机号'}
       ]"
    />
    <template v-if="!isOut">
      <van-field autocomplete="off"
        v-model="legal_id_card"
        :readonly="disabled"
        name="legal_id_card"
        label="法人身份证号"
        placeholder="请输入法人身份证号"
        maxlength="18"
        required
        :rules="[
          {required: true, message: '请填写'},
          {pattern: idPattern, message: '请输入正确身份证号码'}
        ]"
      />
      <van-field autocomplete="off"
        name="legal_positive_path"
        label="上传法人身份证的正面"
        required
        :rules="[{required: true, message: '身份证的正面图片未上传'}]"
        :readonly="disabled"
      >
        <template #input>
          <van-uploader
            :delete="(positive_path_url = '')"
            v-model="legal_positive_path"
            :max-count="1"
            :preview-options="{
              closeable: true,
            }"
            :after-read="uploadCompanyImg_positive"
            :deletable="deletable"
          />
        </template>
      </van-field>
      <van-field autocomplete="off"
        name="legal_negative_path"
        label="上传法人身份证的背面"
        required
        :rules="[{required: true, message: '身份证的背面图片未上传'}]"
        :readonly="disabled"
      >
        <template #input>
          <van-uploader
            :delete="(negative_path_url = '')"
            v-model="legal_negative_path"
            :max-count="1"
            :preview-options="{
              closeable: true,
            }"
            :after-read="uploadCompanyImg_negative"
            :deletable="deletable"
          />
        </template>
      </van-field>
      <div>
        <van-field autocomplete="off"
          readonly
          clickable
          :value="legal_idCard_start_time"
          name="legal_idCard_start_time"
          label="法人身份证有效期的起始日期"
          placeholder="请输入法人身份证有效期的起始日期"
          :readonly="disabled"
          required
          :rules="[{required: true, message: '未填写'}]"
          @click="toShowStartDate"
        />
        <van-popup v-model="showStartPicker" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="选择年月日"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="confirmStartDate"
            @cancel="showStartPicker = false"
          />
        </van-popup>
      </div>

      <!--  身份证是否为长期有效 -->
      <van-field autocomplete="off" name="isLongTime" label="法人身份证是否为长期有效" v-if="isLongTimeList.length"
                 :rules="[{ required: true, message: '未选择' }]" required :readonly="disabled">
        <template #input>
          <van-radio-group v-model="isLongTime" direction="horizontal" style="margin-bottom: -10px"
                           :readonly="disabled">
            <van-radio v-for="item in isLongTimeList" :name="item.key" :key="item.key"
                       style="margin-bottom: 10px">{{item.value}}</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <div v-if="!isLongTime" >
        <van-field autocomplete="off"
          readonly
          clickable
          :value="legal_idCard_end_time"
          name="legal_idCard_end_time"
          label="法人身份证有效期的结束日期"
          placeholder="请输入法人身份证有效期的结束日期"
          :readonly="disabled"
          required
          :rules="[{required: true, message: '未填写'}]"
          @click="toShowEndDate"
        />
        <van-popup v-model="showEndPicker" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="选择年月日"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="confirmEndDate"
            @cancel="showEndPicker = false"
          />
        </van-popup>
      </div>
      <van-field autocomplete="off"
        v-model="line_user_name"
        name="line_user_name"
        label="联系人姓名"
        :readonly="disabled"
        placeholder="请输入联系人姓名"
        required
        :rules="[{required: true, message: '请填写'}]"
      />
      <van-field autocomplete="off"
        v-model="line_user_mobile"
        type="number"
        name="line_user_mobile"
        label="联系人手机号"
        placeholder="请输入联系人手机号"
        :readonly="disabled"
        required
        :rules="[
        {required: true, message: '手机号未填写'},
        {pattern: phoneReg, message: '请输入正确手机号'}
       ]"
      />
    </template>
    <van-field autocomplete="off" name="authorization" label="授权书（公司授权给个人的委托书, 需加盖公章）" :readonly="disabled">
      <template #input>
        <van-uploader
          :show-upload="!disabled"
          :delete="(auth_url = '')"
          v-model="authorization"
          :preview-options="{
            closeable: true,
          }"
          :max-count="1"
          :after-read="uploadCompanyImg_auth"
          :deletable="deletable"
        />
      </template>
    </van-field>
    <template v-if="!isOut">
      <van-field autocomplete="off"
        v-model="qq_num"
        name="qq_num"
        label="QQ"
        placeholder="请输入QQ"
        :readonly="disabled"
      />
      <van-field autocomplete="off"
        v-model="wx_num"
        name="wx_num"
        label="微信"
        placeholder="请输入微信"
        :readonly="disabled"
      />
      <van-field autocomplete="off" v-model="email" name="email" label="邮箱" placeholder="请输入邮箱" :readonly="disabled" />
    </template>
    <van-field autocomplete="off"
      v-model="business_license_number"
      name="business_license_number"
      label="营业执照号"
      placeholder="请输入营业执照号"
      :readonly="disabled"
      required
      :rules="[{required: true, message: '请填写'}]"
    />
    <van-field autocomplete="off"
      name="business_license"
      label="营业执照"
      required
      :readonly="disabled"
      :rules="[{required: true, message: '请上传营业执照'}]"
    >
      <template #input>
        <van-uploader
          :delete="(business_license_url = '')"
          v-model="business_license"
          :max-count="1"
          :after-read="uploadCompanyImg_license"
          :deletable="deletable"
        />
      </template>
    </van-field>
    <van-field autocomplete="off" name="enterprise_qualification" label="企业资质" :readonly="disabled">
      <template #input>
        <van-uploader
          :show-upload="!disabled"
          @delete="toDeleteAnyPreviewPhoto_qualification"
          v-model="enterprise_qualification"
          :max-count="9"
          :preview-options="{
            closeable: true,
          }"
          :after-read="uploadCompanyImg_qualification"
          :deletable="deletable"
        />
      </template>
    </van-field>
    <div style="margin: 16px">
      <van-button
        round
        block
        v-show="(allUserInfo.company_certification_state === 0 && allUserInfo.certification_state === 2) || isUpdate"
        :type="isUpdate ? 'danger' : 'info'"
        native-type="submit"
      >{{ isUpdate ? '修改' : '提交' }}</van-button>
    </div>
  </van-form>
</template>

<script>
import {mapGetters} from 'vuex'
import {Toast} from 'vant'
import Zanwu from '@/assets/zanwu.png'
import comFullAddress from './comFullAddress'
import {idCardReg, phoneReg} from '../constants/comUtils'
import {el} from 'date-fns/locale'
import {cosUploadImg} from '@/utils/cosUpload.js'


const isLongTimeList = [
  {
    key: 0,
    value: '否'
  },
  {
    key: 1,
    value: '是'
  }
];

export default {
  name: 'comEnterpriseAuth',
  props: {
    enterpriseObj: Object,
    isOut: false,
    // true,: true
  },
  components: {
    comFullAddress
  },
  data() {
    return {
      // 图片预览时是否可删除,
      // 默认是可删除, 但是一旦提交认证过就不可删除
      disabled: false,
      deletable: true,
      currentState: '未认证， 请先认证！',
      isUpdate: false,

      // delay_time: 6000,

      company_name: '',
      company_logo: [],
      company_logo_url: [],

      // 用于显示专用
      showFullAddressObj: {
        region_four_name: '',
        detail_address: ''
      },

      // 定义地理位置的初始状态
      // 必须和接口字段一模一样
      regions: {
        provinceid: '',
        provincename: '',
        cityid: '',
        cityname: '',
        areaid: '',
        areaname: '',
        streetid: '',
        streetname: '',
        villageid: '',
        villagename: '',
        address: '',
        FulleAddress: '',
        long: '',
        lat: ''
      },

      company_phone: '',
      legal_name: '',
      legal_name_phone: '',
      legal_id_card: '',
      legal_positive_path: [],
      idPattern: idCardReg,
      phoneReg,

      positive_path_url: '',
      legal_negative_path: [],
      negative_path_url: '',
      legal_idCard_start_time: '',
      isLongTime: 0,
      isLongTimeList,
      legal_idCard_end_time: '',

      line_user_name: '',
      line_user_mobile: '',

      authorization: [],
      auth_url: '',

      qq_num: '',
      wx_num: '',
      email: '',

      business_license_number: '',
      business_license: [],
      business_license_url: '',

      // 企业资质
      enterprise_qualification: [],
      enterprise_qualification_url: [],

      showStartPicker: false,
      showEndPicker: false,
      showPopup: false,
      minDate: new Date(1950, 0, 1),
      maxDate: new Date(2100, 10, 1),
      currentDate: new Date()
    }
  },

  computed: {
    ...mapGetters(['allUserInfo'])
  },

  watch: {
    enterpriseObj: {
      deep: true,
      handler(newValue) {
        if (JSON.stringify(newValue) != '{}') {
          // 更新状态
          this.company_name = newValue.name

          if (newValue.audit_state*1 === 3) {
            // 验证审核失败时,
            this.disabled = false
            this.deletable = true
            this.isUpdate = true
            // this.delay_time = 600
          } else {
            this.disabled = true
            this.deletable = false
            this.isUpdate = false
          }

          /*if (newValue.logo) {
            const arr = newValue.logo.split('|');
            this.company_logo_2 = newValue.logo.split('|').map(itemUrlStr => ({url: itemUrlStr}) );
            this.company_logo.push({url: newValue.logo})
          } else {
            this.company_logo.push({url: Zanwu})
          }*/

          if (this.isOut) {
            // 若有认证数据，则更新regions状态, 必须一一对应
            this.regions.provinceid = newValue.province_id
            this.regions.provincename = newValue.province_name
            this.regions.cityid = newValue.city_id
            this.regions.cityname = newValue.city_name
            this.regions.areaid = newValue.area_id
            this.regions.areaname = newValue.area_name
            this.regions.streetid = newValue.street_id
            this.regions.streetname = newValue.street_name
            this.regions.villageid = newValue.village_id
            this.regions.villagename = newValue.village_name
            this.regions.address = newValue.address
            this.regions.FulleAddress = newValue.full_address
            this.regions.long = newValue.lng
            this.regions.lat = newValue.lat

            // 若有认证数据，则状态子组件显示数据
            this.showFullAddressObj.region_four_name =
              newValue.province_name + newValue.city_name + newValue.area_name + newValue.street_name
            this.showFullAddressObj.detail_address = newValue.address
          } else {
            this.regions.provinceid = newValue.regions.province_id
            this.regions.provincename = newValue.regions.province_name
            this.regions.cityid = newValue.regions.city_id
            this.regions.cityname = newValue.regions.city_name
            this.regions.areaid = newValue.regions.area_id
            this.regions.areaname = newValue.regions.area_name
            this.regions.streetid = newValue.regions.street_id
            this.regions.streetname = newValue.regions.street_name
            this.regions.villageid = newValue.regions.village_id
            this.regions.villagename = newValue.regions.village_name
            this.regions.address = newValue.regions.address
            this.regions.FulleAddress = newValue.regions.full_address
            this.regions.long = newValue.regions.lng
            this.regions.lat = newValue.regions.lat

            // 若有认证数据，则状态子组件显示数据
            this.showFullAddressObj.region_four_name =
              newValue.regions.province_name +
              newValue.regions.city_name +
              newValue.regions.area_name +
              newValue.regions.street_name
            this.showFullAddressObj.detail_address = newValue.regions.address
          }
          // 这是由于van-uploader组件渲染时， 执行了delete方法。
          // 因此使用this.$nextTick。dom渲染完后，再执行，然后更新状态。
          this.$nextTick(() => {

            // 需要的图片链接地址
            // 照片logo
            this.company_logo_url = newValue.logo ? newValue.logo.split('|'): [];
            this.positive_path_url = newValue.legal_positive_path
            this.negative_path_url = newValue.legal_negative_path
            this.auth_url = newValue.authorization
            this.business_license_url = newValue.business_license
            // 资质
            this.enterprise_qualification_url = newValue.enterprise_qualification ? newValue.enterprise_qualification.split('|') : [];
          })

          this.company_phone = newValue.line_phone
          this.legal_name = newValue.legal_name
          this.legal_id_card = newValue.legal_cardno
          this.legal_name_phone = newValue.legal_name_phone
          this.legal_positive_path.push({url: newValue.legal_positive_path})
          this.legal_negative_path.push({url: newValue.legal_negative_path})

          this.legal_idCard_start_time = newValue.legal_validity_start_time
            ? this.$needDateFormat(newValue.legal_validity_start_time, 'yyyy-MM-dd')
            : '';

          // 若是有值，则表示不是长期的
          this.isLongTime = newValue.legal_validity_end_time ? 0 : 1;

          this.legal_idCard_end_time = newValue.legal_validity_end_time
            ? this.$needDateFormat(newValue.legal_validity_end_time, 'yyyy-MM-dd')
            : ''

          this.line_user_name = newValue.line_user_name
          this.line_user_mobile = newValue.line_user_mobile
          newValue.authorization && this.authorization.push({url: newValue.authorization});
          this.qq_num = newValue.qq_num
          this.wx_num = newValue.wx_num
          this.email = newValue.email
          this.business_license_number = newValue.business_license_number
          this.business_license.push({url: newValue.business_license});

          newValue.enterprise_qualification && (
            this.enterprise_qualification = newValue.enterprise_qualification.split('|').map(itemUrlStr => ({url: itemUrlStr}))
          );
          newValue.logo && ( this.company_logo = newValue.logo.split('|').map(itemUrlStr => ({url: itemUrlStr})) );
        }
      }
    }
  },

  methods: {
    toShowStartDate() {
      this.showStartPicker = !this.disabled
    },

    toShowEndDate() {
      this.showEndPicker = !this.disabled
    },

    // 封装组件，得到由子组件传递来的数据
    // toGetFullAddress_*** 由于标识某个页面的地址：如企业认证页、发布页、demo页
    // 参数keyWord 用于标识某个页面中有多个，若只需要一个，则参数keyWord就是noKey

    // 修改regions的数据
    toGetFullAddress_company(regions, keyWord) {
      this.regions = regions
    },

    // 修改四级地址（清空详细地址）
    toUpdateRegionFourName(newObj) {
      this.showFullAddressObj.region_four_name = newObj.region_four_name
      this.showFullAddressObj.detail_address = ''
    },

    // 修改详细地址
    toUpdateDetailAddress(newValue) {
      this.showFullAddressObj.detail_address = newValue
    },

    // 封装公共的上传图片函数
    async _reqUploadPicture(picture) {
      let formData = new FormData()
      formData.append('filename', picture.file)
      // 公司认证的图片
      const img_type = 'company_certification'
      // const res = await this.$api.uploadImg.uploadPhotos(formData, img_type)
      const res = await cosUploadImg(picture.file, img_type)
      if (res.code === 200) {
        return res.data
      }
    },

    uploadCompanyImg_logo(picture) {
      picture.status = 'uploading'
      picture.message = '上传中...'
      this._reqUploadPicture(picture).then(res => {
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed'
          picture.message = '上传失败'
        } else {
          picture.status = 'done'
        }

        // this.company_logo_url = res
        this.company_logo_url.push(res)
      })
    },

    // 删除文件预览时，修改数据
    toDeleteAnyPreviewPhoto_company_logo(file, detail) {
      if (this.company_logo_url.length === 0) {
        this.company_logo_url = []
      } else {
        // splice方法会改变原始数组
        this.company_logo_url.splice(detail.index, 1)
      }
    },


    uploadCompanyImg_positive(picture) {
      picture.status = 'uploading'
      picture.message = '上传中...'
      this._reqUploadPicture(picture).then(res => {
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed'
          picture.message = '上传失败'
        } else {
          picture.status = 'done'
        }
        this.positive_path_url = res
      })
    },

    uploadCompanyImg_negative(picture) {
      picture.status = 'uploading'
      picture.message = '上传中...'
      this._reqUploadPicture(picture).then(res => {
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed'
          picture.message = '上传失败'
        } else {
          picture.status = 'done'
        }
        this.negative_path_url = res
      })
    },

    uploadCompanyImg_auth(picture) {
      picture.status = 'uploading'
      picture.message = '上传中...'
      this._reqUploadPicture(picture).then(res => {
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed'
          picture.message = '上传失败'
        } else {
          picture.status = 'done'
        }
        this.auth_url = res
      })
    },

    uploadCompanyImg_license(picture) {
      picture.status = 'uploading'
      picture.message = '上传中...'
      this._reqUploadPicture(picture).then(res => {
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed'
          picture.message = '上传失败'
        } else {
          picture.status = 'done'
        }
        this.business_license_url = res
      })
    },

    uploadCompanyImg_qualification(picture) {
      picture.status = 'uploading'
      picture.message = '上传中...'
      this._reqUploadPicture(picture).then(res => {
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed'
          picture.message = '上传失败'
        } else {
          picture.status = 'done'
        }
        // this.enterprise_qualification_url = res;
        this.enterprise_qualification_url.push(res);
      })
    },

    toDeleteAnyPreviewPhoto_qualification(file, detail) {
      if (this.enterprise_qualification_url.length === 0) {
        this.enterprise_qualification_url = []
      } else {
        // splice方法会改变原始数组
        this.enterprise_qualification_url.splice(detail.index, 1)
      }
    },

    confirmStartDate(time) {
      this.legal_idCard_start_time = this.$needDateFormat(time, 'yyyy-MM-dd');
      this.showStartPicker = false
    },

    confirmEndDate(time) {
      this.legal_idCard_end_time = this.$needDateFormat(time, 'yyyy-MM-dd');
      this.showEndPicker = false
    },

    onSubmit(values) {
      const {
        company_name,
        company_phone,
        legal_name,
        legal_id_card,
        legal_name_phone,
        legal_idCard_start_time,
        legal_idCard_end_time,
        line_user_name,
        line_user_mobile,
        qq_num,
        wx_num,
        email,
        business_license_number,
        isLongTime,
      } = values

      if (this.legal_idCard_start_time.replace(/-/g, '') * 1 >= this.legal_idCard_end_time.replace(/-/g, '') * 1 && !isLongTime ) {
        Toast('法人身份证起止日期不合法，请修改')
      } else {

        const params = {
          company_name,
          // 数组转为字符串
          company_logo: this.company_logo_url.join('|'),

          regions: this.regions,

          linePhone: company_phone,
          legal_name,
          id_card: legal_id_card,
          legal_name_phone: legal_name_phone,
          legal_positive_path: this.positive_path_url,
          legal_negative_path: this.negative_path_url,
          legal_validity_start_time: legal_idCard_start_time,
          // 是否长期有效
          legal_validity_end_time: isLongTime ? '长期有效' : legal_idCard_end_time,
          line_user_name,
          line_user_mobile,
          authorization: this.auth_url,
          qq_num,
          wx_num,
          email,
          business_license_number,
          business_license: this.business_license_url,
          // 数组转为字符串
          enterprise_qualification: this.enterprise_qualification_url.join('|'),
        }

        sessionStorage.setItem('params', JSON.stringify(params))

        this.$emit('getEnterpriseAuthValue', params)
      }
    }
  }
}
</script>

<style scoped>
.isError {
  border: 1px solid red;
}
</style>
